//
//  HLUserAccountViewModel.swift
//  weibo-snh
//
//  Created by 黄力 on 15/12/14.
//  Copyright © 2015年 HLTest. All rights reserved.
//

import UIKit
import AFNetworking

class HLUserAccountViewModel: NSObject {
    
    //定义一个用户数据模型的属性
    var userAccount: HLUserAccount?
    //定义一个计算型属性来获取当前的登录状态
    var loginStatus: Bool {
        get {
            return userAccount?.access_token != nil
        }
    }
    //返回用户的头像地址
    var userImageStr: String? {
        get {
            return userAccount?.avatar_large
        }
    }
    //返回用户的昵称
    var userName: String? {
        get {
            return userAccount?.name
        }
    }
    //返回用户的token
    var userToken: String? {
        get {
            return userAccount?.access_token
        }
    }
    
    //重写初始化方法
    override init() {
        userAccount = HLUserAccount.getUserAccount()
        super.init()
    }
    
    //请求token
    func loadUserToken (code: String, finshed: (success: Bool) -> ()) {
        
        let parameters = ["client_id":OAuthAppKey,"client_secret":OAuthAppSecret,"grant_type":"authorization_code","code":code,"redirect_uri":OAuthAppRedirect]
        
        HLNetworking.sharedNetworking.sendHTTPRequest(.POST, urlStr: "oauth2/access_token", parameters: parameters) { (resultData, error) -> () in
            //判断请求数据是否成功
            if error == nil {
                //根据获取的token去请求用户信息
                self.loadUserInfo(resultData!,finshed: finshed)
            }else {
                finshed(success: false)
            }
        }
        
    }
    
    //请求用户信息
    private func loadUserInfo (resultDic: [String: AnyObject],finshed: (success: Bool) -> ()) {
        //将用户数据转换成模型
        let userAccount = HLUserAccount(dic: resultDic)
        //获取字典里的数据
        let access_token = resultDic["access_token"] as! String
        //        let expires_in = resultDic["expires_in"] as! Double
        let uid = resultDic["uid"] as! String
        //设置请求参数
        let parameters = ["access_token": access_token, "uid": uid]
        
        HLNetworking.sharedNetworking.sendHTTPRequest(.GET, urlStr: "2/users/show.json", parameters: parameters) { (resultData, error) -> () in
            //判断请求数据是否成功
            if error == nil {
                //获取用户的昵称
                let name = resultData!["name"] as! String
                //获取用户头像
                let avatar_large = resultData!["avatar_large"] as! String
                //保存到模型中
                userAccount.name = name
                userAccount.avatar_large = avatar_large
                //保存到沙盒
                userAccount.saveToSanbox()
                finshed(success: true)
            }else {
                finshed(success: false)
            }
        }
        
        
    }

    
}
